Python的有序集合:设置集合顺序的方法

您所在的位置:网站首页 Python 集合排序 Python的有序集合:设置集合顺序的方法

Python的有序集合:设置集合顺序的方法

2023-10-21 13:23| 来源: 网络整理| 查看: 265

What is Python Ordered Set and How to Preserve Order of Set

作为一个有序的集合,没有内置的功能,但许多包可以帮助你使用OrderedSet。 至于 Python 3.7 和 CPython 3.6,正则 dict 被证实可以保持秩序,并且比OrderedDict 性能更好。

要把 dictionary 用作有序集,在保持秩序的同时过滤掉重复的元素,可以模拟一个有序集。

Python 有序集

要在Python 中使用 有序 集,请使用ordered-set 包。也有其他软件包可用。

ordered-set(基于Python) orderedset(基于CPython) collection-extended boltons(在iterutils.IndexedSet下,基于Python的) oset 排序的容器 在Python中使用boltons的OrderedSet

为了使用 boltonsIndexSet,你需要安装boltons 包。

python3 -m pip install boltons

现在,使用下面的代码导入该模块。

from boltons.setutils import IndexedSet

让我们使用IndexedSet并将两个列表作为参数传递。

from boltons.setutils import IndexedSet data = IndexedSet(list(range(2)) + list(range(3, 6))) print(data) 输出 IndexedSet([0, 1, 3, 4, 5])

现在,让我们改变列表的顺序,同时将其传递给IndexedSet。

from boltons.setutils import IndexedSet data = IndexedSet(list(range(3, 6)) + list(range(2))) print(data) 输出 IndexedSet([3, 4, 5, 0, 1])

你可以看到,这个集合的顺序被完美地保留了下来。它保留了它们被添加到 Python 集合中的顺序。

在 Python 中使用 sortedcontainers 的 OrderedSet

Python sortedcontainers模块提供了一个 SortedSet,用于保留集合元素的顺序。使用sortedcontainers有一些好处,包括纯Python、快速的as-C实现、100%的单元测试覆盖率,以及数小时的压力测试。

让我们使用pip 软件包管理器来安装sortedcontainers 模块。

python3 -m pip install sortedcontainers

现在,使用下面的代码导入该模块。

from sortedcontainers import SortedSet

让我们使用**SortedSet()**方法,将两个列表作为参数传递。

from sortedcontainers import SortedSet data = SortedSet(list(range(2)) + list(range(3, 6))) print(data) 输出 SortedSet([0, 1, 3, 4, 5])

你可以看到,返回的集合默认是以升序排序的。

现在,让我们在传递给SortedSet的同时改变列表的顺序。

from sortedcontainers import SortedSet data = SortedSet(list(range(3, 6)) + list(range(2))) print(data) 输出 SortedSet([0, 1, 3, 4, 5])

你可以看到,即使我们以不同的顺序向集合添加元素,它也会默认以升序返回。

Python中的OrderedSet就这样了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3